<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Nav extends Model
{
    protected $dateFormat = 'U';

    /**
     * @param int $type     导航类型
     * @param bool $status  是否只取未软删除
     * @param null $structure 结构
     * @return array
     */
    public static function lists($type=1,$status=false,$structure=null,$mark='child')
    {
        $data = self::where('type',$type)
                    ->orderBy('sort','asc')
                    ->get();

        if($structure=='tree'){
            return self::tree($data->toArray(),0,$mark);
        }
        if($structure=='plumb'){
            return self::plumb($data->toArray(),0,$mark);
        }

        return $data;
    }

    /** 树形结构 */
    public static function tree($model,$pid=0,$child='child')
    {
        $data = array();
        foreach($model as $item){
            if($pid == $item['pid']){
                $item[$child] = self::tree($model,$item['id'],$child);
                $data[] = $item;
            }
        }
        return $data;
    }

    /** 排序结构 */
    public static function plumb($model,$pid=0,$prefix='--')
    {
        $data = array();
        foreach($model as $item){
            if($item['pid']==$pid){
                $item['name'] = $prefix.$item['name'];
                $data[] = $item;
                $child = self::plumb($model,$item['id'],$prefix.$prefix);
                $data = array_merge($data,$child);
            }
        }

        return $data;
    }

    /**
     * 找寻所有父级
     * @param array $nav_ids 指定id的数组
     * @param bool $itself   返回值是否保留原id(包括自身)
     * @return array
     */
    public static function parentsAll($nav_ids = array(),$keep= true)
    {
        $pids = self::whereIn('id',$nav_ids)->where('pid','!=',0)->pluck('pid')->toArray();

        if(!empty($pids)){
            $par_pid = self::parentsAll($pids);// 此处虽然使用递归查询,但占用资源量由父级层数决定
            $pids = array_merge($pids,$par_pid);
        }

        if($keep){
            $pids = array_merge($nav_ids,$pids);
        }

        $nav_ids = array_unique($pids);// 剔除重复值
        return $nav_ids;
    }
}
